package com.example.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.example.config.WhiteUrlsConfig;
import org.example.constant.AuthConstants;
import org.example.constant.BusinessEnum;
import org.example.constant.HttpContains;
import org.example.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Date;

/**
 * 全局token过滤器
 * 前后端预定好的token存放的位置：请求头的Authorization bearer token 其中bear是值
 */
@Component
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {

    @Autowired
    private WhiteUrlsConfig whiteUrlsConfig;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 校验token
     * 1.获取请求路径
     * 2.判断请求路径是否可以放行
     *  放行：不需要验证身份
     *  不放行：需要对其进行身份的认证
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        // 获取请求路径
        String path = request.getPath().toString();

        System.out.println("是否在白名单中："+whiteUrlsConfig.getAllowUrls().contains(path));
        // 判断当前请求路径是否需要放行，是否存在于白名单中
        if (whiteUrlsConfig.getAllowUrls().contains(path)) {
            //包含在白名单中，放行
            return chain.filter(exchange);
        }

        // 不包含在白名单中，进行身份认证
        // 从约定好的位置获取Authorization值， 值的格式为：bearer token
        String authorizationValue = request.getHeaders().getFirst(AuthConstants.AUTHORIZATION);
        // 判断是否有值
        if (StringUtils.hasText(authorizationValue)){
            //从authorization中获取token
            //判断authorization中token是含有"Bearer
            String tokenValue="";
            if (StringUtils.hasText(authorizationValue) && authorizationValue.startsWith(AuthConstants.BEARER)){
                tokenValue=authorizationValue.replaceFirst(AuthConstants.BEARER, "");
            }
            if (StringUtils.hasText(authorizationValue) && authorizationValue.startsWith(AuthConstants.MINIBEARER)){
                tokenValue=authorizationValue.replaceFirst(AuthConstants.MINIBEARER, "");
            }

            //判断redis中是否存在该token
            if(StringUtils.hasText(tokenValue) && stringRedisTemplate.hasKey(AuthConstants.LOGIN_TOKEN_PREFIX+tokenValue)){
                //身份验证通过
                return chain.filter(exchange);
            }
        }

        //身份验证失败或请求不合法
        log.error("拦截非法请求，时间:{}，请求API路径:{}",new Date(), path);

        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //设置响应头信息
        response.getHeaders().set(HttpContains.CONTENT_TYPE, HttpContains.APPLICATION_JSON);

        //设置响应消息
         Result<Object> result=Result.fail(BusinessEnum.UN_AUTHORIZED);

         //创建一个ObjectMapper对象
         ObjectMapper objectMapper=new ObjectMapper();
         byte[] bytes = new byte[0];
         try {
             bytes = objectMapper.writeValueAsBytes(result);
         } catch (Exception e) {
             throw new RuntimeException(e);
         }
         DataBuffer dataBuffer = response.bufferFactory().wrap(bytes);
         return response.writeWith(Mono.just(dataBuffer));
    }

    @Override
    public int getOrder() {
        return -5;
    }
}
